/**
 *
 * @description: ticket获取
 * @author: junyong.hong
 * @createTime: 2018/10/12
 * @version: 1.0.0.0
 * @history:
 *    1、
 *    2、
 *
 */
// schema 描述数据字段
// model  数据模型
// entity 一条数据的实例
const mongoose = require('mongoose')
const Schema = mongoose.Schema

const TicketSchema = new Schema({
    // accessTicket
    name: String,
    ticket: String,
    // 失效时间
    expires_in: Number,
    meta: {
        createdAt: {
            type: Date,
            default: Date.now()
        },
        updatedAt: {
            type: Date,
            default: Date.now()
        }
    }
})

TicketSchema.pre('save', function (next) {
    // 如果是新增的
    if (this.isNew) {
        this.meta.createdAt = this.meta.updatedAt = Date.now()
    } else {
        this.meta.updatedAt = Date.now()
    }

    next()
})

// 静态方法
TicketSchema.statics = {
    async getTicket () {
        // 先查ticket
        const ticket = await this.findOne({
            name: 'ticket'
        })

        if (ticket && ticket.ticket) {
            ticket.ticket = ticket.ticket
        }

        return ticket
    },

    async saveTicket (data) {
        console.log('data', data)
        // 先查ticket
        let ticket = await this.findOne({
            name: 'ticket'
        })

        if (ticket) {
            ticket.ticket = data.ticket
            ticket.expires_in = data.expires_in
        } else {
            ticket = new Ticket({
                name: 'ticket',
                ticket: data.ticket,
                expires_in: data.expires_in
            })
        }

        await ticket.save()

        return data
    }
}

const Ticket = mongoose.model('Ticket', TicketSchema)
